﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Songhay
{
    /// <summary>
    /// Defines the grouping and completion-tracking of asynchronous operations.
    /// </summary>
    /// <remarks>
    /// This class is a poor substitute for what is lacking in Silverlight 4
    /// (and older) with regard to features in the Task Parallel Library.
    /// </remarks>
    public class AsyncOperationGroup
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncOperationGroup"/> class.
        /// </summary>
        /// <param name="numberOfOperations">The number of operations.</param>
        /// <param name="completionAction">The completion action.</param>
        public AsyncOperationGroup(byte numberOfOperations, Action completionAction)
        {
            if(completionAction == null) throw new ArgumentNullException("completionAction", "The completion action is null.");
            this._completionAction = completionAction;
            this._asyncOperationCompletionList = new bool[numberOfOperations];
        }

        /// <summary>
        /// Marks the operation complete.
        /// </summary>
        /// <param name="operationOrdinal">The zero-based operation ordinal.</param>
        public void MarkOperationComplete(byte operationOrdinal)
        {
            if(operationOrdinal >= this._asyncOperationCompletionList.Length)
                throw new ArgumentException("The ordinal is not in the completion list.", "operationOrdinal");
            this._asyncOperationCompletionList[operationOrdinal] = true;
            if(this._asyncOperationCompletionList.Count(i => i) != this._asyncOperationCompletionList.Count()) return;
            this._completionAction.Invoke();
        }

        Action _completionAction;
        bool[] _asyncOperationCompletionList;
    }
}
